package com.flow.engine.service.impl;

import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.flow.engine.entity.FlowAuditUser;
import com.flow.engine.entity.User;
import com.flow.engine.enums.standard.ApprovalState;
import com.flow.engine.mapper.FlowAuditUserMapper;
import com.flow.engine.service.FlowAuditUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;

/**
 * @author ly163
 */
@Service
public class FlowAuditUserServiceImpl extends ServiceImpl<FlowAuditUserMapper, FlowAuditUser> implements FlowAuditUserService {


    @Autowired
    private FlowAuditUserMapper mapper;

    @Override
    public List<FlowAuditUser> queryByFlowNodeId(Long currentNodeId) {
        return mapper.selectList(Wrappers.<FlowAuditUser>lambdaQuery().eq(FlowAuditUser::getFlowNodeId, currentNodeId));
    }

    @Override
    @Transactional
    public Boolean updateByFlowNodeId(Long currentNodeId, User user, String auditRemark, ApprovalState approvalState, ApprovalState otherApprovalState) {
        String auditUserId = user.getId();
        FlowAuditUser fau = FlowAuditUser.builder().auditRemark(auditRemark).auditTime(LocalDateTime.now()).approvalState(approvalState).build();
        LambdaUpdateWrapper<FlowAuditUser> w2 = Wrappers.<FlowAuditUser>lambdaUpdate().eq(FlowAuditUser::getFlowNodeId, currentNodeId).eq(FlowAuditUser::getAuditUserId, auditUserId);
        mapper.update(fau, w2);
        LambdaUpdateWrapper<FlowAuditUser> w1 = Wrappers.<FlowAuditUser>lambdaUpdate().eq(FlowAuditUser::getFlowNodeId, currentNodeId).ne(FlowAuditUser::getAuditUserId, auditUserId);
        fau.setAuditRemark(null);
        fau.setApprovalState(otherApprovalState);
        return mapper.update(fau, w1) > 0;
    }

    @Override
    public Boolean updateByFlowNodeIdAndAuditUserId(Long currentNodeId, String id, ApprovalState nodeApprovalState, String auditRemark) {
        return update(Wrappers.<FlowAuditUser>lambdaUpdate().eq(FlowAuditUser::getFlowNodeId, currentNodeId).eq(FlowAuditUser::getAuditUserId, id).set(FlowAuditUser::getApprovalState, nodeApprovalState).set(FlowAuditUser::getAuditRemark, auditRemark).set(FlowAuditUser::getAuditTime, LocalDateTime.now()));
    }

    @Override
    public List<FlowAuditUser> queryByFlowNodeIds(List<Long> nextNodes) {
        return mapper.selectList(Wrappers.<FlowAuditUser>lambdaQuery().in(FlowAuditUser::getFlowNodeId, nextNodes));
    }


}
